package prostagra;

import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class PanelGry extends JPanel
{

    private Gra gra;
    private boolean paused = false;
    private AnimationThread thread;
    private ClickThread clickThread;    //the time in miliseconds between every repaint.
    private int sleeptime = 60;

    public PanelGry()
    {
    }

    public PanelGry(Gra g, int x, int y)
    {
        this.setPreferredSize(new Dimension(x, y));
        this.setMinimumSize(new Dimension(x, y));
        this.setMaximumSize(new Dimension(x, y));
        gra = g;
        gra.setSzerokosc(this.getPreferredSize().width);
        gra.setWysokosc(this.getPreferredSize().height);

        //gra.setup(initInput());
        gra.setup();
        clickThread = new ClickThread(gra);
        this.setBackground(Color.green);
        this.addMouseListener(clickThread);

    }


    public void setPause(boolean p)
    {
        paused = p;
    }

    public void start()
    {
        thread = new AnimationThread(this);
        thread.start();
        clickThread.start();
        //gra.gameLoop();
        gra.start();
    }

    public void setSleepTime(int ms)
    {
        sleeptime = ms;
    }

    public void stop()
    {
        gra.stop();
    }

    public boolean isPaused()
    {
        return paused;
    }

    @Override
    public void paint(Graphics g)
    {
        gra.setWysokosc(this.getHeight());
        gra.setSzerokosc(this.getWidth());
        gra.draw((Graphics2D) g);
    }

    class AnimationThread extends Thread
    {

        private PanelGry gp;

        AnimationThread(PanelGry g)
        {
            gp = g;
        }

        @Override
        public void run()
        {
            while (true)
            {
                try
                {
                    sleep(sleeptime);
                } catch (Exception e)
                {
                    e.printStackTrace(System.err);
                }

                if (!gp.isPaused())
                {
                    gp.repaint();
                }
            }
        }
    }

    class ClickThread extends Thread implements MouseListener
    {

        private Gra gp;

        ClickThread(Gra g)
        {
            gp = g;

        }



        public void mouseClicked(MouseEvent e)
        {
            //System.out.println("s");
        }

        public void mousePressed(MouseEvent e)
        {
            gra.mousePressed(e);
        }

        public void mouseReleased(MouseEvent e)
        {
            gra.mouseReleased(e);
        }

        public void mouseEntered(MouseEvent e)
        {
            //System.out.println("s");
        }

        public void mouseExited(MouseEvent e)
        {
            //System.out.println("s");
        }
    }
}
